<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智慧社区数据分析看板</title>
    <link rel="stylesheet" href="../lib/Font-Awesome-6.4.0/css/all.min.css">
    <script src="../js/echarts.min.js"></script>
    <script src="../js/html2canvas.min.js"></script>
    <script src="../js/jspdf.umd.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --primary: #3498db;
            --primary-light: #5dade2;
            --secondary: #1abc9c;
            --secondary-light: #76d7c4;
            --card-bg: #ffffff;
            --light-bg: #f8f9fa;
            --text-dark: #2c3e50;
            --text-medium: #34495e;
            --text-light: #7f8c8d;
            --border-color: #e0e7ed;
            --success: #2ecc71;
            --warning: #f39c12;
            --danger: #e74c3c;
            --shadow: 0 6px 20px rgba(175, 197, 222, 0.15);
            --light-shadow: 0 3px 10px rgba(175, 197, 222, 0.1);
        }

        body {
            background-color: #ffffff; /* 确保背景为纯白色 */
            color: var(--text-dark);
            padding: 20px;
            min-height: 100vh;
        }

        .dashboard-container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 25px 30px;
            background: #ffffff;
            border-radius: 18px;
            box-shadow: var(--shadow);
            border: 1px solid var(--border-color);
        }

        .header h1 {
            display: flex;
            align-items: center;
            font-size: 2.2rem;
            font-weight: 700;
            color: var(--text-dark);
        }

        .header h1 i {
            margin-right: 15px;
            color: var(--primary);
            font-size: 2.4rem;
            background: linear-gradient(to right, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .date-time {
            background-color: #edf7ff;
            padding: 10px 20px;
            border-radius: 12px;
            font-size: 1.1rem;
            color: var(--text-medium);
            font-weight: 500;
            border: 1px solid var(--border-color);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: var(--card-bg);
            border-radius: 18px;
            padding: 30px;
            box-shadow: var(--shadow);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            border: 1px solid var(--border-color);
            text-align: left;
        }

        .stat-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 15px 30px rgba(175, 197, 222, 0.2);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .card-header h3 {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--text-light);
            letter-spacing: 0.3px;
        }

        .card-header i {
            font-size: 1.6rem;
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, var(--primary-light), var(--primary));
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
        }

        .card-body {
            display: flex;
            flex-direction: column;
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
            background: linear-gradient(to right, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            letter-spacing: -1px;
        }

        .stat-description {
            font-size: 0.95rem;
            color: var(--text-medium);
            line-height: 1.6;
        }

        .charts-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 30px;
            margin-bottom: 40px;
        }

        .chart-container {
            background: var(--card-bg);
            border-radius: 18px;
            padding: 25px;
            box-shadow: var(--shadow);
            transition: all 0.3s ease;
            position: relative;
            min-height: 380px;
            overflow: hidden;
            border: 1px solid var(--border-color);
        }

        .chart-container:hover {
            box-shadow: 0 15px 35px rgba(175, 197, 222, 0.2);
        }

        .chart-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .chart-title h2 {
            font-size: 1.4rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            color: var(--text-dark);
        }

        .chart-title h2 i {
            margin-right: 12px;
            color: var(--primary);
            background: linear-gradient(to right, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .chart-actions {
            display: flex;
            gap: 10px;
        }

        .action-btn {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            background: #edf7ff;
            color: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
        }

        .action-btn:hover {
            background: var(--primary);
            color: white;
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
        }

        .chart-content {
            width: 100%;
            height: calc(100% - 70px);
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.95);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
            border-radius: 18px;
        }

        .loading-spinner {
            border: 4px solid rgba(52, 152, 219, 0.15);
            border-top: 4px solid var(--primary);
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        .loading-text {
            color: var(--text-medium);
            font-size: 1.1rem;
            font-weight: 500;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error-message {
            color: var(--danger);
            font-weight: 600;
            text-align: center;
            padding: 20px;
        }

        /* 全屏模式样式 */
        .full-screen-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.97);
            z-index: 1000;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
        }

        .full-screen-chart {
            width: 90%;
            height: 85%;
            position: relative;
            background: var(--card-bg);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 25px 60px rgba(0, 0, 0, 0.08);
            border: 1px solid var(--border-color);
        }

        .close-btn {
            position: absolute;
            top: 25px;
            right: 25px;
            width: 50px;
            height: 50px;
            background: #f8f9fa;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 1.5rem;
            transition: all 0.3s ease;
            z-index: 1010;
            color: var(--text-light);
            border: 1px solid var(--border-color);
            box-shadow: var(--light-shadow);
        }

        .close-btn:hover {
            background: var(--primary);
            color: white;
            transform: rotate(90deg);
            border-color: var(--primary);
        }

        .chart-full-title {
            font-size: 1.8rem;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            padding-left: 20px;
            font-weight: 600;
            color: var(--text-dark);
        }

        .chart-full-title i {
            margin-right: 15px;
            color: var(--primary);
            background: linear-gradient(to right, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* 响应式布局 */
        @media (max-width: 1200px) {
            .charts-container {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                text-align: center;
                gap: 20px;
            }

            .date-time {
                width: 100%;
            }

            .stat-number {
                font-size: 2rem;
            }

            .chart-container {
                min-height: 320px;
            }

            .header h1 {
                font-size: 1.8rem;
            }
        }
        /* 报告生成按钮 */
        .report-btn {
            background: linear-gradient(135deg, #3498db, #1abc9c);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
            transition: all 0.3s ease;
        }

        .report-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }

        /* 报告容器 */
        .report-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            z-index: 2000;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 30px;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.4s ease;
        }

        .report-container.active {
            opacity: 1;
            pointer-events: all;
        }

        .report-content {
            width: 100%;
            max-width: 1000px;
            height: 90%;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            box-shadow: 0 25px 60px rgba(0, 0, 0, 0.3);
        }

        .report-header {
            background: linear-gradient(135deg, #3498db, #1abc9c);
            color: white;
            padding: 25px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .report-title {
            font-size: 1.8rem;
            font-weight: 700;
        }

        .report-actions {
            display: flex;
            gap: 15px;
        }

        .report-action-btn {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .report-action-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        .report-body {
            flex: 1;
            overflow-y: auto;
            padding: 30px 40px;
        }

        .report-section {
            margin-bottom: 40px;
        }

        .section-title {
            font-size: 1.5rem;
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3498db;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .section-title i {
            color: #3498db;
        }

        .data-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .summary-card {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        }

        .summary-title {
            font-size: 1rem;
            color: #7f8c8d;
            margin-bottom: 10px;
        }

        .summary-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #3498db;
        }

        .recommendation-card {
            background: #edf7ff;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            border-left: 4px solid #3498db;
        }

        .recommendation-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
        }

        .recommendation-icon {
            width: 50px;
            height: 50px;
            background: #3498db;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }

        .recommendation-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .recommendation-content {
            line-height: 1.7;
            color: #34495e;
        }

        .report-chart-container {
            height: 300px;
            margin: 25px 0;
            border: 1px solid #e0e7ed;
            border-radius: 15px;
            overflow: hidden;
        }

        .chart-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #f8f9fa;
            color: #7f8c8d;
            font-style: italic;
        }

        .report-footer {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-size: 0.9rem;
            border-top: 1px solid #e0e7ed;
        }

        /* 加载动画 */
        .report-loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
        }

        .report-spinner {
            width: 60px;
            height: 60px;
            border: 5px solid rgba(52, 152, 219, 0.2);
            border-top: 5px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        .report-loading-text {
            font-size: 1.2rem;
            color: #34495e;
            font-weight: 500;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
<div class="dashboard-container">
    <div class="header">
        <h1><i class="fas fa-chart-line"></i> 智慧社区数据分析看板</h1>
        <div class="date-time">
            <span id="current-date">2025年7月12日 星期六 13:31:45</span>
        </div>
        <!-- 添加报告生成按钮 -->
        <button class="report-btn" id="generate-report">
            <i class="fas fa-file-alt"></i> 生成分析报告
        </button>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="card-header">
                <h3>居民总人数</h3>
                <i class="fas fa-users"></i>
            </div>
            <div class="card-body">
                <div class="stat-number" id="resident-count">--</div>
                <p class="stat-description">实时数据统计 | 较上周增长5.2%</p>
            </div>
        </div>

        <div class="stat-card">
            <div class="card-header">
                <h3>当月订单数</h3>
                <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="card-body">
                <div class="stat-number" id="order-count">--</div>
                <p class="stat-description">较上月增长 8.7% | 高于社区平均水平</p>
            </div>
        </div>

        <div class="stat-card">
            <div class="card-header">
                <h3>物业缴费率</h3>
                <i class="fas fa-wallet"></i>
            </div>
            <div class="card-body">
                <div class="stat-number" id="fee-rate">--</div>
                <p class="stat-description">超过行业平均水平 | 位列区域榜首</p>
            </div>
        </div>
    </div>

    <div class="charts-container">
        <!-- 居民性别分布图表 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载居民性别分布数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-venus-mars"></i> 居民性别分布</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="gender">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="residentGenderDistribution"></div>
        </div>

        <!-- 费用类型分布图表 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载费用类型分布数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-money-bill-wave"></i> 费用类型分布</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="fee">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="feeTypeDistribution"></div>
        </div>

        <!-- 楼栋房屋数量统计图表 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载楼栋房屋数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-building"></i> 楼栋房屋数量统计</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="building">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="propertyBuildingDistribution"></div>
        </div>
        <!-- 近6个月缴费金额趋势图 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载缴费金额趋势数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-chart-line"></i> 近6个月缴费金额趋势</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="monthlyFeeTrend">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="monthlyFeeTrend"></div>
        </div>
        <!-- 每月维修请求数量趋势图 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载维修请求数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-tools"></i> 每月维修请求数量趋势</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="maintenanceTrend">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="maintenanceTrend"></div>
        </div>

        <!-- 投诉处理状态分布图 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载投诉处理数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-exclamation-triangle"></i> 投诉处理状态分布</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="complaintStatus">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="complaintStatusDistribution"></div>
        </div>

        <!-- 停车位使用情况统计图 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载停车位数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-parking"></i> 停车位使用情况统计</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="parkingStatus">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="parkingStatusDistribution"></div>
        </div>

        <!-- 热销商品销售数量排行图 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载热销商品数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-shopping-bag"></i> 热销商品销售数量排行</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="topProducts">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="topProductsChart"></div>
        </div>

        <!-- 健康服务预约类型占比图 -->
        <div class="chart-container">
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载健康服务数据...</div>
            </div>
            <div class="chart-title">
                <h2><i class="fas fa-heartbeat"></i> 健康服务预约类型占比</h2>
                <div class="chart-actions">
                    <div class="action-btn expand-btn" data-chart="healthServices">
                        <i class="fas fa-expand"></i>
                    </div>
                </div>
            </div>
            <div class="chart-content" id="healthServicesDistribution"></div>
        </div>

    </div>
</div>
<!-- 报告容器 -->
<div class="report-container" id="report-container">
    <div class="report-content">
        <div class="report-header">
            <div class="report-title">智慧社区数据分析报告</div>
            <div class="report-actions">
                <div class="report-action-btn" id="print-report" title="打印报告">
                    <i class="fas fa-print"></i>
                </div>
                <div class="report-action-btn" id="download-report" title="下载PDF">
                    <i class="fas fa-download"></i>
                </div>
                <div class="report-action-btn" id="close-report" title="关闭报告">
                    <i class="fas fa-times"></i>
                </div>
            </div>
        </div>

        <div class="report-body" id="report-body">
            <!-- 报告内容将通过JavaScript动态生成 -->
        </div>

        <div class="report-footer">
            报告生成时间: <span id="report-time"></span> | 智慧社区数据分析系统
        </div>
    </div>
</div>

<!-- 全屏图表容器 -->
<div id="fullscreen-container" class="full-screen-overlay" style="display: none;">
    <div class="close-btn">
        <i class="fas fa-times"></i>
    </div>
    <div id="fullscreen-chart" class="full-screen-chart"></div>
</div>

<script>
    // 设置全局 fetch 请求头
    const originalFetch = window.fetch;

    window.fetch = function(input, init = {}) {
        // 获取 localStorage 中的 user 数据
        try {
            const userData = localStorage.getItem('user');
            if (userData) {
                const data = JSON.parse(userData);
                if (data && data.token) {
                    // 为请求添加 Authorization 头部
                    if (!init.headers) {
                        init.headers = {};
                    }
                    init.headers['Authorization'] = 'Bearer ' + data.token;
                }
            }
        } catch (e) {
            console.error("解析 user 数据失败:", e);
        }

        // 调用原生 fetch 发起请求
        return originalFetch(input, init);
    };
</script>
<script>
    // 更新当前日期时间
    function updateDateTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        const day = now.getDate();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');

        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const weekday = weekdays[now.getDay()];

        document.getElementById('current-date').textContent = `${year}年${month}月${day}日 ${weekday} ${hours}:${minutes}:${seconds}`;
    }

    // 初始化图表
    function initCharts() {
        // 居民性别分布图表
        const genderChart = echarts.init(document.getElementById('residentGenderDistribution'));

        // 费用类型分布图表
        const feeChart = echarts.init(document.getElementById('feeTypeDistribution'));

        // 楼栋房屋数量统计图表
        const buildingChart = echarts.init(document.getElementById('propertyBuildingDistribution'));

        // 近6个月缴费金额趋势图
        const monthlyFeeChart = echarts.init(document.getElementById('monthlyFeeTrend'));

        // 每月维修请求数量趋势图
        const maintenanceChart = echarts.init(document.getElementById('maintenanceTrend'));

        // 投诉处理状态分布图
        const complaintChart = echarts.init(document.getElementById('complaintStatusDistribution'));

        // 停车位使用情况统计图
        const parkingChart = echarts.init(document.getElementById('parkingStatusDistribution'));

        // 热销商品销售数量排行图
        const productsChart = echarts.init(document.getElementById('topProductsChart'));

        // 健康服务预约类型占比图
        const healthChart = echarts.init(document.getElementById('healthServicesDistribution'));

        // 保存图表实例
        window.charts = {
            gender: genderChart,
            fee: feeChart,
            building: buildingChart,
            monthlyFeeTrend: monthlyFeeChart,
            maintenanceTrend: maintenanceChart,
            complaintStatus: complaintChart,
            parkingStatus: parkingChart,
            topProducts: productsChart,
            healthServices: healthChart
        };
    }

    // 请求相关
    function fetchDashboardData() {
        fetch('/empStatistics/dashboard')
            .then(response => response.json())
            .then(res => {
                if (res.code === 0) {
                    const data = res.data;
                    document.getElementById('resident-count').textContent = data.residentCount.toLocaleString();
                    document.getElementById('order-count').textContent = data.orderCount.toLocaleString() + '';
                    document.getElementById('fee-rate').textContent = data.feeRate.toFixed(1) + '%';
                } else {
                    console.error('居民总数请求失败:', res.msg);
                }
            })
            .catch(error => {
                console.error('请求居民总数失败:', error);
                document.getElementById('resident-count').textContent = '--';
                document.getElementById('order-count').textContent = '--';
                document.getElementById('fee-rate').textContent = '--';
            });
    }

    // 数据
    function fetchGenderData() {
        const chart = window.charts.gender;
        const container = document.querySelector('#residentGenderDistribution').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/residentGenderDistribution')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;
                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c}人 ({d}%)',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#3498db',
                            padding: 12,
                            textStyle: { color: '#34495e' }
                        },
                        legend: {
                            bottom: 10,
                            left: 'center',
                            textStyle: { color: '#34495e' }
                        },
                        color: ['#3498db', '#e74c3c'],
                        series: [
                            {
                                name: '性别',
                                type: 'pie',
                                radius: ['40%', '70%'],
                                center: ['50%', '45%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 10,
                                    borderColor: '#ffffff',
                                    borderWidth: 2
                                },
                                label: {
                                    show: false,
                                    position: 'center',
                                    color: '#34495e'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: 18,
                                        fontWeight: 'bold',
                                        color: '#34495e'
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: data
                            }
                        ]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }

    // 请求费用类型分布数据
    function fetchFeeData() {
        const chart = window.charts.fee;
        const container = document.querySelector('#feeTypeDistribution').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/feeTypeDistribution')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;
                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c}元 ({d}%)',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#1abc9c',
                            padding: 12,
                            textStyle: { color: '#34495e' }
                        },
                        legend: {
                            orient: 'vertical',
                            right: 10,
                            top: 'center',
                            textStyle: { color: '#34495e' }
                        },
                        color: ['#1abc9c', '#3498db', '#f1c40f', '#e74c3c', '#9b59b6'],
                        series: [
                            {
                                name: '费用类型',
                                type: 'pie',
                                radius: ['30%', '65%'],
                                center: ['40%', '50%'],
                                roseType: 'radius',
                                itemStyle: {
                                    borderRadius: 8,
                                    borderColor: '#ffffff',
                                    borderWidth: 2
                                },
                                label: {
                                    color: '#34495e'
                                },
                                data: data
                            }
                        ]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }

    // 请求楼栋房屋数据
    function fetchBuildingData() {
        const chart = window.charts.building;
        const container = document.querySelector('#propertyBuildingDistribution').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/propertyBuildingDistribution')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;
                    const option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { type: 'shadow' },
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#3498db',
                            textStyle: { color: '#34495e' },
                            padding: 12
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '10%',
                            top: '10%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            name: '楼栋编号',
                            data: data.map(item => item.name),
                            axisLabel: {
                                interval: 0,
                                rotate: 0,
                                color: '#7f8c8d'
                            },
                            axisLine: {
                                lineStyle: {
                                    color: '#d5dce0'
                                }
                            },
                            axisTick: {
                                show: false
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '房屋数量',
                            nameLocation: 'end',
                            nameTextStyle: {
                                color: '#7f8c8d',
                                padding: [0, 0, 0, 50]
                            },
                            splitLine: {
                                lineStyle: {
                                    color: '#e0e7ed'
                                }
                            },
                            axisLabel: {
                                color: '#7f8c8d'
                            },
                            axisLine: {
                                show: false
                            }
                        },
                        series: [
                            {
                                name: '房屋数量',
                                type: 'bar',
                                data: data.map(item => item.value),
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#3498db' },
                                        { offset: 1, color: '#1abc9c' }
                                    ]),
                                    borderRadius: [8, 8, 0, 0]
                                },
                                label: {
                                    show: true,
                                    position: 'top',
                                    color: '#3498db',
                                    fontWeight: 'bold'
                                }
                            }
                        ]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }

    // 请求近6个月缴费金额趋势数据
    function fetchMonthlyFeeTrend() {
        const chart = window.charts.monthlyFeeTrend;
        const container = document.querySelector('#monthlyFeeTrend').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/monthlyFeeTrend')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;

                    const option = {
                        tooltip: {
                            trigger: 'axis',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#3498db',
                            padding: 12,
                            textStyle: { color: '#34495e' },
                            formatter: '{b}: {c}元'
                        },
                        xAxis: {
                            type: 'category',
                            data: data.map(item => item.name), // 使用 name
                            axisLabel: { color: '#7f8c8d' },
                            axisLine: { lineStyle: { color: '#d5dce0' } },
                            axisTick: { show: false }
                        },
                        yAxis: {
                            type: 'value',
                            name: '金额（元）',
                            nameTextStyle: { color: '#7f8c8d', padding: [0, 0, 0, 50] },
                            splitLine: { lineStyle: { color: '#e0e7ed' } },
                            axisLabel: { color: '#7f8c8d' },
                            axisLine: { show: false }
                        },
                        series: [{
                            name: '缴费金额',
                            type: 'line',
                            data: data.map(item => item.value), // 修正为 value
                            smooth: true,
                            symbol: 'circle',
                            symbolSize: 8,
                            itemStyle: {
                                color: '#3498db',
                                borderColor: '#ffffff',
                                borderWidth: 2
                            },
                            lineStyle: {
                                width: 3,
                                color: '#3498db'
                            },
                            areaStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(52, 152, 219, 0.5)' },
                                    { offset: 1, color: 'rgba(52, 152, 219, 0.1)' }
                                ])
                            },
                            label: {
                                show: true,
                                position: 'top',
                                color: '#3498db',
                                fontWeight: 'bold',
                                formatter: '{c}元'
                            }
                        }]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `
              <div class="error-message">
                请求失败: ${error.message}<br>
                <button onclick="fetchMonthlyFeeTrend()" style="margin-top: 10px;">重试</button>
              </div>`;
            });
    }


    // 请求每月维修请求数量趋势数据
    function fetchMaintenanceTrendData() {
        const chart = window.charts.maintenanceTrend;
        const container = document.querySelector('#maintenanceTrend').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/maintenanceTrend')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;

                    const option = {
                        tooltip: {
                            trigger: 'axis',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#f39c12',
                            padding: 12,
                            textStyle: { color: '#34495e' },
                            formatter: '{b}: {c}次'
                        },
                        xAxis: {
                            type: 'category',
                            data: data.map(item => item.name), // 统一使用 name
                            axisLabel: { color: '#7f8c8d' },
                            axisLine: { lineStyle: { color: '#d5dce0' } },
                            axisTick: { show: false }
                        },
                        yAxis: {
                            type: 'value',
                            name: '维修次数',
                            nameTextStyle: { color: '#7f8c8d', padding: [0, 0, 0, 50] },
                            splitLine: { lineStyle: { color: '#e0e7ed' } },
                            axisLabel: { color: '#7f8c8d' },
                            axisLine: { show: false }
                        },
                        series: [{
                            name: '维修次数',
                            type: 'line',
                            data: data.map(item => item.value), // 统一使用 value
                            smooth: true,
                            symbol: 'circle',
                            symbolSize: 8,
                            itemStyle: {
                                color: '#f39c12',
                                borderColor: '#ffffff',
                                borderWidth: 2
                            },
                            lineStyle: { width: 3, color: '#f39c12' },
                            areaStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(243, 156, 18, 0.5)' },
                                    { offset: 1, color: 'rgba(243, 156, 18, 0.1)' }
                                ])
                            },
                            label: {
                                show: true,
                                position: 'top',
                                color: '#f39c12',
                                fontWeight: 'bold',
                                formatter: '{c}次'
                            }
                        }]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }


    // 请求投诉处理状态分布数据
    function fetchComplaintStatusData() {
        const chart = window.charts.complaintStatus;
        const container = document.querySelector('#complaintStatusDistribution').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/complaintStatusDistribution')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;

                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c}件 ({d}%)',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#e74c3c',
                            padding: 12,
                            textStyle: { color: '#34495e' }
                        },
                        legend: {
                            bottom: 10,
                            left: 'center',
                            textStyle: { color: '#34495e' }
                        },
                        color: ['#e74c3c', '#f39c12', '#2ecc71'],
                        series: [{
                            name: '投诉状态',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['50%', '45%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#ffffff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center',
                                color: '#34495e'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 18,
                                    fontWeight: 'bold',
                                    color: '#34495e'
                                }
                            },
                            labelLine: { show: false },
                            data: data.map(item => ({
                                value: item.value,
                                name: item.name
                            }))
                        }]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }

    // 请求停车位使用情况统计数据
    function fetchParkingStatusData() {
        const chart = window.charts.parkingStatus;
        const container = document.querySelector('#parkingStatusDistribution').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/parkingStatusDistribution')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;

                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c}个 ({d}%)',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#9b59b6',
                            padding: 12,
                            textStyle: { color: '#34495e' }
                        },
                        legend: {
                            bottom: 10,
                            left: 'center',
                            textStyle: { color: '#34495e' }
                        },
                        color: ['#2ecc71', '#e74c3c'],
                        series: [{
                            name: '停车位状态',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['50%', '45%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#ffffff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center',
                                color: '#34495e'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 18,
                                    fontWeight: 'bold',
                                    color: '#34495e'
                                }
                            },
                            labelLine: { show: false },
                            data: data.map(item => ({
                                value: item.value,
                                name: item.name
                            }))
                        }]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }


    // 请求热销商品销售数量排行数据
    function fetchTopProductsData() {
        const chart = window.charts.topProducts;
        const container = document.querySelector('#topProductsChart').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/topProducts')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;
                    const option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { type: 'shadow' },
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#3498db',
                            textStyle: { color: '#34495e' },
                            padding: 12,
                            formatter: '{b}: {c}件'
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '10%',
                            top: '10%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: data.map(item => item.name),
                            axisLabel: {
                                interval: 0,
                                rotate: 30,
                                color: '#7f8c8d'
                            },
                            axisLine: {
                                lineStyle: {
                                    color: '#d5dce0'
                                }
                            },
                            axisTick: {
                                show: false
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '销售量',
                            nameLocation: 'end',
                            nameTextStyle: {
                                color: '#7f8c8d',
                                padding: [0, 0, 0, 50]
                            },
                            splitLine: {
                                lineStyle: {
                                    color: '#e0e7ed'
                                }
                            },
                            axisLabel: {
                                color: '#7f8c8d'
                            },
                            axisLine: {
                                show: false
                            }
                        },
                        series: [{
                            name: '销售量',
                            type: 'bar',
                            data: data.map(item => item.value),
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: '#3498db' },
                                    { offset: 1, color: '#1abc9c' }
                                ]),
                                borderRadius: [8, 8, 0, 0]
                            },
                            label: {
                                show: true,
                                position: 'top',
                                color: '#3498db',
                                fontWeight: 'bold'
                            }
                        }]
                    };
                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
            });
    }

    // 请求健康服务预约类型占比数据
    function fetchHealthServicesData() {
        const chart = window.charts.healthServices;
        const container = document.querySelector('#healthServicesDistribution').parentElement;
        const loadingOverlay = container.querySelector('.loading-overlay');

        fetch('/empStatistics/healthServicesDistribution')
            .then(response => response.json())
            .then(res => {
                loadingOverlay.style.display = 'none';

                if (res.code === 0) {
                    const data = res.data;

                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c}次 ({d}%)',
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderColor: '#e74c3c',
                            padding: 12,
                            textStyle: { color: '#34495e' }
                        },
                        legend: {
                            bottom: 10,
                            left: 'center',
                            textStyle: { color: '#34495e' }
                        },
                        color: ['#e74c3c', '#3498db', '#f1c40f', '#2ecc71'],
                        series: [{
                            name: '服务类型',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['50%', '45%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#ffffff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center',
                                color: '#34495e'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 18,
                                    fontWeight: 'bold',
                                    color: '#34495e'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: data.map(item => ({
                                value: item.value,
                                name: item.name
                            }))
                        }]
                    };

                    chart.setOption(option);
                } else {
                    loadingOverlay.innerHTML = `<div class="error-message">数据加载失败: ${res.msg}</div>`;
                }
            })
            .catch(error => {
                loadingOverlay.innerHTML = `
              <div class="error-message">
                请求失败: ${error.message}<br>
                <button onclick="fetchHealthServicesData()" style="margin-top: 10px;">重试</button>
              </div>`;
            });
    }


    // 初始化全屏功能
    function initFullScreen() {
        const overlay = document.getElementById('fullscreen-container');
        const closeBtn = overlay.querySelector('.close-btn');
        const fullscreenChart = document.getElementById('fullscreen-chart');

        // 关闭全屏
        closeBtn.addEventListener('click', function() {
            overlay.style.display = 'none';
            fullscreenChart.innerHTML = '';
        });

        // 图表放大按钮事件
        document.querySelectorAll('.expand-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const chartType = this.dataset.chart;
                const chartInstance = window.charts[chartType];

                // 设置全屏显示的图表
                overlay.style.display = 'flex';
                fullscreenChart.innerHTML = '<div class="chart-full-title"><i class="fas"></i><span></span></div><div class="chart-content"></div>';

                // 设置标题
                let chartTitle, iconClass;
                switch(chartType) {
                    case 'gender':
                        chartTitle = '居民性别分布';
                        iconClass = 'fa-venus-mars';
                        break;
                    case 'fee':
                        chartTitle = '费用类型分布';
                        iconClass = 'fa-money-bill-wave';
                        break;
                    case 'building':
                        chartTitle = '楼栋房屋数量统计';
                        iconClass = 'fa-building';
                        break;
                    case 'monthlyFeeTrend':
                        chartTitle = '近6个月缴费金额趋势';
                        iconClass = 'fa-chart-line';
                        break;
                    case 'maintenanceTrend':
                        chartTitle = '每月维修请求数量趋势';
                        iconClass = 'fa-tools';
                        break;
                    case 'complaintStatus':
                        chartTitle = '投诉处理状态分布';
                        iconClass = 'fa-exclamation-triangle';
                        break;
                    case 'parkingStatus':
                        chartTitle = '停车位使用情况统计';
                        iconClass = 'fa-parking';
                        break;
                    case 'topProducts':
                        chartTitle = '热销商品销售数量排行';
                        iconClass = 'fa-shopping-bag';
                        break;
                    case 'healthServices':
                        chartTitle = '健康服务预约类型占比';
                        iconClass = 'fa-heartbeat';
                        break;
                }

                fullscreenChart.querySelector('.chart-full-title i').className = `fas ${iconClass}`;
                fullscreenChart.querySelector('.chart-full-title span').textContent = chartTitle;

                // 创建新的图表实例
                const chartContent = fullscreenChart.querySelector('.chart-content');
                const fullChart = echarts.init(chartContent);
                fullChart.setOption(chartInstance.getOption());

                // 调整图表大小
                setTimeout(() => fullChart.resize(), 50);

                // 窗口大小调整时重新调整图表大小
                const resizeHandler = () => fullChart.resize();
                window.addEventListener('resize', resizeHandler);

                // 关闭时移除事件监听
                closeBtn.addEventListener('click', function cleanup() {
                    window.removeEventListener('resize', resizeHandler);
                    closeBtn.removeEventListener('click', cleanup);
                });
            });
        });
    }

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 更新日期时间
        updateDateTime();
        setInterval(updateDateTime, 1000); // 每秒更新一次时间

        // 初始化图表
        initCharts();

        // 获取数据
        fetchDashboardData();
        fetchGenderData();
        fetchFeeData();
        fetchBuildingData();
        fetchMonthlyFeeTrend();
        fetchMaintenanceTrendData();
        fetchComplaintStatusData();
        fetchParkingStatusData();
        fetchTopProductsData();
        fetchHealthServicesData();

        // 初始化全屏功能
        initFullScreen();

        // 窗口大小调整时重新调整图表大小
        window.addEventListener('resize', function() {
            if (window.charts) {
                Object.values(window.charts).forEach(chart => {
                    chart.resize();
                });
            }
        });
    });
    // 计算平均每月维修请求数
    function calculateAvgMaintenanceRequests(maintenanceData) {
        if (!maintenanceData.length) return 'N/A';
        const total = maintenanceData.reduce((sum, item) => sum + item.value, 0);
        return (total / maintenanceData.length).toFixed(1);
    }

    // 渲染报告图表
    function renderReportChart(data) {
        const chartContainer = document.getElementById('dynamic-chart-container');
        if (!chartContainer) return;

        chartContainer.innerHTML = '<div class="chart-placeholder">加载中...</div>';
        setTimeout(() => {
            chartContainer.innerHTML = '';
            const chart = echarts.init(chartContainer);
            const option = {
                tooltip: { trigger: 'axis' },
                xAxis: {
                    type: 'category',
                    data: data.monthlyFee.map(item => item.name),
                    axisLabel: { color: '#7f8c8d' }
                },
                yAxis: { type: 'value', name: '金额（元）' },
                series: [{
                    name: '缴费金额',
                    type: 'line',
                    smooth: true,
                    data: data.monthlyFee.map(item => item.value),
                    itemStyle: { color: '#3498db' },
                    lineStyle: { color: '#3498db' }
                }]
            };
            chart.setOption(option);
        }, 500);
    }

    // 生成报告内容
    function generateReportContent(data) {
        const reportBody = document.getElementById('report-body');

        // 计算平均每月维修请求数
        const avgMaintenanceRequests = calculateAvgMaintenanceRequests(data.maintenance);

        // 查找预约量最高的健康服务
        const topHealthService = data.healthServices.length > 0 ? data.healthServices.reduce((max, item) => item.value > max.value ? item : max, data.healthServices[0]) : null;

        // 使用真实的楼栋入住率数据
        const buildingOccupancy = data.buildingOccupancy;

        // 计算整体入住率及最高/最低楼栋
        let averageOccupancy = 'N/A';
        let maxOccupancyBuilding = 'N/A';
        let minOccupancyBuilding = 'N/A';
// 使用模拟数据代替写死值
        const mockBuildingOccupancy = [
            { name: "A栋", occupancyRate: 85.0 },
            { name: "B栋", occupancyRate: 75.0 },
            { name: "C栋", occupancyRate: 60.0 },
            { name: "D栋", occupancyRate: 90.0 },
            { name: "E栋", occupancyRate: 45.0 }
        ];

        if (Array.isArray(buildingOccupancy) && buildingOccupancy.length > 0) {
            const totalOccupancy = buildingOccupancy.reduce((sum, b) => sum + b.occupancyRate, 0);
            averageOccupancy = (totalOccupancy / buildingOccupancy.length).toFixed(1) + '%';
            const maxOccupancy = buildingOccupancy.reduce((max, b) =>
                b.occupancyRate > max.occupancyRate ? b : max, buildingOccupancy[0]);
            const minOccupancy = buildingOccupancy.reduce((min, b) =>
                b.occupancyRate < min.occupancyRate ? b : min, buildingOccupancy[0]);
            maxOccupancyBuilding = maxOccupancy.name;
            minOccupancyBuilding = minOccupancy.name;
        } else {
            // 如果没有真实数据，则使用模拟数据
            const totalOccupancy = mockBuildingOccupancy.reduce((sum, b) => sum + b.occupancyRate, 0);
            averageOccupancy = (totalOccupancy / mockBuildingOccupancy.length).toFixed(1) + '%';
            const maxOccupancy = mockBuildingOccupancy.reduce((max, b) =>
                b.occupancyRate > max.occupancyRate ? b : max);
            const minOccupancy = mockBuildingOccupancy.reduce((min, b) =>
                b.occupancyRate < min.occupancyRate ? b : min);
            maxOccupancyBuilding = maxOccupancy.name;
            minOccupancyBuilding = minOccupancy.name;
        }

        // 计算停车位使用率
        const parkingStats = data.parking.reduce((acc, item) => {
            acc[item.name] = item.value;
            return acc;
        }, {});
        const totalParkingSpots = Object.values(parkingStats).reduce((a, b) => a + b, 0);
        const occupiedPercentage = totalParkingSpots > 0 ? ((parkingStats['占用'] / totalParkingSpots) * 100).toFixed(1) : '0';

        // 渲染报告内容
        reportBody.innerHTML = `
        <div class="report-section">
            <div class="section-title">
                <i class="fas fa-chart-pie"></i>
                <span>数据概览</span>
            </div>
            <div class="data-summary">
                <div class="summary-card">
                    <div class="summary-title">居民总人数</div>
                    <div class="summary-value">${data.dashboard.residentCount || '--'}</div>
                </div>
                <div class="summary-card">
                    <div class="summary-title">当月订单数</div>
                    <div class="summary-value">${data.dashboard.orderCount || '--'}</div>
                </div>
                <div class="summary-card">
                    <div class="summary-title">物业缴费率</div>
                    <div class="summary-value">${data.dashboard.feeRate ? data.dashboard.feeRate.toFixed(1) + '%' : '--'}</div>
                </div>
                <div class="summary-card">
                    <div class="summary-title">平均每月维修请求数</div>
                    <div class="summary-value">${avgMaintenanceRequests}</div>
                </div>
            </div>
            <div class="section-title">
                <i class="fas fa-lightbulb"></i>
                <span>关键洞察</span>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-users"></i></div>
                    <div class="recommendation-title">居民增长趋势</div>
                </div>
                <div class="recommendation-content">
                    社区总人数达 ${data.dashboard.residentCount || '--'} 人，建议在新开发区域增加配套服务设施。
                </div>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-shopping-cart"></i></div>
                    <div class="recommendation-title">消费行为分析</div>
                </div>
                <div class="recommendation-content">
                    热门商品：${data.topProducts.length ? data.topProducts[0].name : '暂无'}。
                    建议优化供应链并设置晚间促销活动。
                </div>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-tools"></i></div>
                    <div class="recommendation-title">维修服务优化</div>
                </div>
                <div class="recommendation-content">
                    平均每月维修请求数为 ${avgMaintenanceRequests} 次，建议根据请求量调整维修人员配置。
                </div>
            </div>
        </div>
        <div class="report-section">
            <div class="section-title">
                <i class="fas fa-chart-line"></i>
                <span>核心指标趋势图</span>
            </div>
            <div class="report-chart-container" id="dynamic-chart-container">
                <!-- 图表将通过 JavaScript 渲染 -->
            </div>
        </div>
        <div class="report-section">
            <div class="section-title">
                <i class="fas fa-clipboard-list"></i>
                <span>详细数据分析</span>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-home"></i></div>
                    <div class="recommendation-title">房屋入住情况</div>
                </div>
                <div class="recommendation-content">
                    当前社区整体入住率达到 ${averageOccupancy}，
                    其中${maxOccupancyBuilding}入住率最高，${minOccupancyBuilding}入住率最低，建议推出租赁优惠。
                </div>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-car"></i></div>
                    <div class="recommendation-title">停车位使用分析</div>
                </div>
                <div class="recommendation-content">
                    根据停车位使用数据，晚间使用率达到 ${occupiedPercentage}%，建议优化停车位分配策略。
                </div>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-heartbeat"></i></div>
                    <div class="recommendation-title">健康服务需求</div>
                </div>
                <div class="recommendation-content">
                    健康服务预约中，${topHealthService ? topHealthService.name : '暂无数据'} 预约量最高，建议增加相关服务频次。
                </div>
            </div>
        </div>
        <div class="report-section">
            <div class="section-title">
                <i class="fas fa-tasks"></i>
                <span>行动建议</span>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-check-circle"></i></div>
                    <div class="recommendation-title">短期行动 (1个月内)</div>
                </div>
                <div class="recommendation-content">
                    <ul>
                        <li>在低入住率楼栋（如${minOccupancyBuilding}）开展租赁优惠活动</li>
                        <li>优化商城生鲜供应链，减少缺货率</li>
                        <li>增加晚间促销活动，提升销售额</li>
                        <li>每栋楼配备基础维修工具包，缩短响应时间</li>
                    </ul>
                </div>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-calendar-alt"></i></div>
                    <div class="recommendation-title">中期计划 (1-3个月)</div>
                </div>
                <div class="recommendation-content">
                    <ul>
                        <li>增设停车位以缓解晚间停车压力</li>
                        <li>每月开展健康服务相关讲座</li>
                        <li>开发社区APP实现在线报修</li>
                        <li>优化绿化布局，提升休闲空间</li>
                    </ul>
                </div>
            </div>
            <div class="recommendation-card">
                <div class="recommendation-header">
                    <div class="recommendation-icon"><i class="fas fa-chart-line"></i></div>
                    <div class="recommendation-title">长期战略 (3-6个月)</div>
                </div>
                <div class="recommendation-content">
                    <ul>
                        <li>建立社区数据分析平台</li>
                        <li>开发智能停车系统</li>
                        <li>建设社区健康服务中心</li>
                        <li>实施能源管理系统</li>
                    </ul>
                </div>
            </div>
        </div>
    `;

        // 渲染图表
        renderReportChart(data);
    }

    // 报告生成功能
    document.getElementById('generate-report').addEventListener('click', function () {
        const reportContainer = document.getElementById('report-container');
        const reportBody = document.getElementById('report-body');
        const reportTime = document.getElementById('report-time');

        // 显示加载动画
        reportBody.innerHTML = `
        <div class="report-loading">
            <div class="report-spinner"></div>
            <div class="report-loading-text">正在从服务器加载最新数据...</div>
        </div>
    `;
        reportContainer.classList.add('active');

        // 并行请求所有图表数据
        Promise.all([
            fetch('/empStatistics/dashboard').then(res => res.json()),
            fetch('/empStatistics/residentGenderDistribution').then(res => res.json()),
            fetch('/empStatistics/feeTypeDistribution').then(res => res.json()),
            fetch('/empStatistics/propertyBuildingDistribution').then(res => res.json()),
            fetch('/empStatistics/monthlyFeeTrend').then(res => res.json()),
            fetch('/empStatistics/maintenanceTrend').then(res => res.json()),
            fetch('/empStatistics/complaintStatusDistribution').then(res => res.json()),
            fetch('/empStatistics/parkingStatusDistribution').then(res => res.json()),
            fetch('/empStatistics/topProducts').then(res => res.json()),
            fetch('/empStatistics/healthServicesDistribution').then(res => res.json()),
            fetch('/empStatistics/buildingOccupancy').then(res => res.json())
        ]).then(([dashboardRes, genderRes, feeRes, buildingRes, monthlyFeeRes,
                     maintenanceRes, complaintRes, parkingRes, topProductsRes, healthRes, buildingOccupancyRes]) => {
            const data = {
                dashboard: dashboardRes.code === 0 ? dashboardRes.data : {},
                gender: genderRes.code === 0 ? genderRes.data : [],
                feeType: feeRes.code === 0 ? feeRes.data : [],
                buildings: buildingRes.code === 0 ? buildingRes.data : [],
                monthlyFee: monthlyFeeRes.code === 0 ? monthlyFeeRes.data : [],
                maintenance: maintenanceRes.code === 0 ? maintenanceRes.data : [],
                complaints: complaintRes.code === 0 ? complaintRes.data : [],
                parking: parkingRes.code === 0 ? parkingRes.data : [],
                topProducts: topProductsRes.code === 0 ? topProductsRes.data : [],
                healthServices: healthRes.code === 0 ? healthRes.data : [],
                buildingOccupancy: buildingOccupancyRes.code === 0 ? buildingOccupancyRes.data : []
            };

            // 数据处理和报告生成
            generateReportContent(data);

            // 设置报告时间
            reportTime.textContent = new Date().toLocaleString();
        }).catch(error => {
            console.error('报告生成失败:', error);
            reportBody.innerHTML = `<div class="error-message">数据加载失败，请刷新重试</div>`;
        });
    });

    // 打印报告功能
    document.getElementById('print-report').addEventListener('click', function() {
        window.print();
    });

    // 下载PDF报告功能
    document.getElementById('download-report').addEventListener('click', function () {
        const reportContent = document.querySelector('.report-content');
        const reportBody = document.getElementById('report-body');
        const originalReportBodyContent = reportBody.innerHTML;

        // 显示加载动画
        reportBody.innerHTML = `
        <div class="report-loading">
            <div class="report-spinner"></div>
            <div class="report-loading-text">正在生成PDF报告，请稍候...</div>
        </div>
    `;

        setTimeout(() => {
            html2canvas(reportContent, { scale: 2 }).then(canvas => {
                const imgData = canvas.toDataURL('image/png');

                const pdf = new jspdf.jsPDF('p', 'mm', 'a4');
                const imgWidth = 210;
                const pageHeight = 297;
                const imgHeight = canvas.height * imgWidth / canvas.width;

                let heightLeft = imgHeight;
                let position = 0;

                pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;

                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                }

                pdf.save('智慧社区分析报告.pdf');

                // 只还原报告正文内容，保留头部和按钮
                reportBody.innerHTML = originalReportBodyContent;
            }).catch(error => {
                console.error("html2canvas error:", error);
                reportBody.innerHTML = originalReportBodyContent;
                alert("生成PDF失败，请重试！");
            });
        }, 500);
    });


    // 关闭报告
    document.getElementById('close-report').addEventListener('click', function() {
        document.getElementById('report-container').classList.remove('active');
    });

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        updateDateTime();
        setInterval(updateDateTime, 1000);
    });
</script>
</body>
</html>